package model

import (
	"database/sql"

	baseEntity "github.com/lab-online/internal/shared/entity"
	"github.com/lab-online/internal/user/entity"
	"github.com/lab-online/pkg/model"
	"gorm.io/gorm"
)

type User struct {
	model.BaseModel
	Username string `gorm:"unique;index"`
	Name     string
	Password string
	Role     uint8
}

func (u *User) ToEntity() entity.UserEntity {
	return &entity.User{
		Base: baseEntity.Base{
			ID:        u.ID,
			DeletedAt: sql.NullTime(u.DeletedAt),
		},
		Username: u.Username,
		Name:     u.Name,
		Password: u.Password,
		Role:     u.Role,
	}
}

type UserOption func(*User)

func NewUser(opts ...UserOption) *User {
	user := &User{}
	for _, opt := range opts {
		opt(user)
	}
	return user
}

func WithID(id uint) UserOption {
	return func(u *User) {
		u.ID = id
	}
}

func WithUsername(username string) UserOption {
	return func(u *User) {
		u.Username = username
	}
}

func WithName(name string) UserOption {
	return func(u *User) {
		u.Name = name
	}
}

func WithRole(role uint8) UserOption {
	return func(u *User) {
		u.Role = role
	}
}

func WithEntity(e entity.UserEntity) UserOption {
	return func(u *User) {
		u.ID = e.GetID()
		u.Username = e.GetUsername()
		u.Name = e.GetName()
		u.Password = e.GetPassword()
		u.Role = e.GetRole()
		u.DeletedAt = gorm.DeletedAt(e.GetDeletedAt())
	}
}
